package com.ruitaowang.admin.config;

import com.alibaba.fastjson.JSON;
//import com.unicorn.admin.entity.UserToken;
//import com.unicorn.admin.service.UserTokenService;
//import com.unicorn.admin.util.RedisUtil;
//import com.unicorn.admin.web.MsgOut;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author cailei.lu
 * @description
 * @date 2018/8/3
 */
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

//    @Autowired
//    private RedisUtil<String> redisUtil;
//    @Autowired
//    private UserTokenService userTokenService;

    //存放鉴权信息的Header名称，默认是Authorization
    private String httpHeaderName = "Authorization";

    //鉴权失败后返回的HTTP错误码，默认为401
    private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;

    /**
     * 存放登录用户模型Key的Request Key
     */
    public static final String REQUEST_CURRENT_KEY = "REQUEST_CURRENT_KEY";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, accept, content-type");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Allow-Origin", "*");
//        // 如果打上了AuthToken注解则需要验证token
//            String token = request.getHeader(httpHeaderName);
//            log.info("token is {}", token);
//            String userJson = "";
//            //验证redis是否有登录信息
//            if ("app".contains(request.getRequestURI())){
//                UserToken userToken=userTokenService.selectByToken(token);
//                if (!ObjectUtils.isEmpty(userToken)){
//                    userJson=userToken.getUserJson();
//                }
//            }else {
//                if (!ObjectUtils.isEmpty(token)) {
//                    userJson = redisUtil.get(token);
//                    log.info("userJson is {}", userJson);
//                }
//                //验证数据库是否有该登录信息
//                if (ObjectUtils.isEmpty(userJson)){
//                    UserToken userToken=userTokenService.selectByToken(token);
//                    if (!ObjectUtils.isEmpty(userToken)){
//                        if (userToken.getEtime() == 0){
//                            userJson=userToken.getUserJson();
//                        }else {
//                            long time=System.currentTimeMillis() - userToken.getEtime();
//                            if (time < 7200000){
//                                userJson=userToken.getUserJson();
//                            }
//                        }
//                    }
//                }
//            }
//            if (!ObjectUtils.isEmpty(userJson)) {
//                redisUtil.set(token,userJson,2, TimeUnit.HOURS);
//                return true;
//            } else {
//                //生成 response 返回值错误数据
//                response.setStatus(unauthorizedErrorCode);
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("text/html; charset=utf-8");
//                MsgOut o=MsgOut.error("您没有访问权限",new ArrayList<String>());
//                o.setCode(401);
//                PrintWriter writer = null;
//                try {
//                    writer=response.getWriter();
//                    writer.append(JSON.toJSONString(o));
//                    writer.flush();
//                    writer.close();
//                    return false;
//                } catch (IOException e){
//                    e.printStackTrace();
//                    writer.flush();
//                    writer.close();
//                    return false;
//                }
//            }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
